package com.simon.study.algorithm.zheda;


/**
 * <p>
 *
 * @author SimonLiu
 * @date 2022/8/31 23:04
 */
public class Demo1 {
    public static final int MAXN = 101;
    public static final int MAXK = 100000;

    @FunctionalInterface
    public interface TriFunction<T, U, V, R>{ R apply(T t, U u, V v); }

    public static Double f1(Integer n, double[] a, Double x) {
        double p = a[0], dx = x.doubleValue();
        int in = n.intValue();
        for (int i = 1; i < in; i++) {
            p += (a[i]*Math.pow(dx, i));
        }
        return p;
    }

    public static Double f2(Integer n, double[] a, Double x) {
        double p = a[0], dx = x.doubleValue();
        int in = n.intValue();

        for (int i = in; i > 0; i--) {
            p += a[i-1] + dx*p;
        }
        return p;
    }

    public static void run(TriFunction<Integer, double[], Double, Double> func, double[] a, int n) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < MAXK; i++) {
            func.apply(MAXN-1, a, 1.1);
        }
        long end   = System.currentTimeMillis();

        long duration = end - start;

        System.out.println("func " + n + " duration is:" + duration);
    }

    public static void main(String[] args) {
        double[] a = new double[MAXN];

        for (int i = 1; i < MAXN; i++) {
            a[i] = 1.0/i;
        }

        run( Demo1::f1, a,1);
        run( Demo1::f2, a,2);
    }
}
